package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"order_srv/cache"
	"order_srv/models/mysql"
	"order_srv/pkg"
	"time"

	"order_srv/internal/svc"
	"order_srv/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderCreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderCreateLogic {
	return &OrderCreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderCreateLogic) OrderCreate(in *order.OrderCreateRequest) (*order.OrderCreateResponse, error) {
	// todo: add your logic here and delete this line
	var goods mysql.Goods
	err := goods.GoodsInfo(in.GoodsId)
	if err != nil {
		logx.Info("商品信息不存在", err)
		return nil, errors.New("商品信息不存在")
	}
	if goods.GoodsStock < in.GoodsNum {
		logx.Info("库存不足", err)
		return nil, errors.New("库存不足")
	}
	orderSn := uuid.NewString()
	amount := goods.GoodsPrice * float64(in.GoodsNum)
	payTime := time.Now().Format("2006-01-02 15:04:05")
	o := mysql.Order{
		UserId:  in.UserId,
		OrderSn: orderSn,
		PayType: 1,
		PayTime: payTime,
		Amount:  amount,
	}
	err = o.Create()
	if err != nil {
		logx.Info("创建订单信息失败", err)
		return nil, errors.New("创建订单信息失败")
	}
	og := mysql.OrderGoods{
		GoodsId:    in.GoodsId,
		OrderId:    int64(o.ID),
		GoodsName:  goods.GoodsName,
		GoodsPrice: goods.GoodsPrice,
		GoodsStock: goods.GoodsStock,
		GoodsCover: goods.GoodsCover,
	}
	err = og.Create()
	if err != nil {
		logx.Info("创建商品订单信息失败", err)
		return nil, errors.New("创建商品订单信息失败")
	}
	cache.DelGoodsStock(int64(goods.ID), in.GoodsNum)
	totalAmount := fmt.Sprintf("%.2F", amount)
	aLiPay := pkg.ALiPay{
		Subject:     "商品支付",
		OutTradeNo:  orderSn,
		TotalAmount: totalAmount,
	}
	UrlPay := aLiPay.Pay()

	return &order.OrderCreateResponse{
		OrderId: int64(o.ID),
		UrlPay:  UrlPay,
	}, nil
}
